package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;
import com.xsherl.leetcode.utils.ArrayUtils;
import com.xsherl.leetcode.utils.PrintUtils;

import java.util.*;

public class Permutations {

    Set<Integer> set = new HashSet<>();

    /**
     * DFS
     *
     * @param nums 1 <= nums.length <= 6
     *             -10 <= nums[i] <= 10
     *             nums 中的所有整数 互不相同
     */
    public List<List<Integer>> permute1(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        permute(nums, new LinkedList<>(), res);
        return res;
    }

    private void permute(int[] nums, LinkedList<Integer> path, List<List<Integer>> res){
        if (path.size() == nums.length){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; ++i){
            if (set.contains(nums[i])){
                continue;
            }
            set.add(nums[i]);
            path.push(nums[i]);
            permute(nums, path, res);
            set.remove(nums[i]);
            path.pop();
        }
    }

    /**
     * 回溯算法
     */
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        for(int n: nums){
            list.add(n);
        }
        permute(0, list, res);
        return res;
    }

    private void permute(int index, List<Integer> list, List<List<Integer>> res){
        if (index == list.size()){
            res.add(new ArrayList<>(list));
            return;
        }
        // 只重新排列index后面的元素，避免重复数据
        for (int i = index; i < list.size(); ++i){
            Collections.swap(list, i, index);
            permute(index + 1, list, res);
            Collections.swap(list, i, index);
        }
    }


    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> permute = new Permutations().permute(nums);
        PrintUtils.println(permute);
        List<List<Integer>> integers = ArrayUtils.parse("[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]");
        Assert.isTrue(ArrayUtils.allMatch(permute, integers));
    }

}
